<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1,maximum-scale=1"/>
    <title>Force Directed Graph</title>
    <link rel="stylesheet" type="text/css" href="../../css/styles.css"/>
    <script type="text/javascript" src="../../lib/d3.js"></script>
</head>

<body>

<script type="text/javascript">
    var w = 1280,
            h = 800,
            r = 4.5,
            colors = d3.scaleOrdinal(d3.schemeCategory20c);

    var force = d3.forceSimulation()
            .velocityDecay(0.8)
            .alphaDecay(0)
            .force("charge", d3.forceManyBody())
            .force("x", d3.forceX(w / 2))
            .force("y", d3.forceY(h / 2));

    var svg = d3.select("body").append("svg")
            .attr("width", w)
            .attr("height", h);

    d3.json("../../data/flare.json", function (data) {
        var root = d3.hierarchy(data); // <-A
        var nodes = root.descendants(); // <-B
        var links = root.links(); // <-C

        force.nodes(nodes); // <-D
        force.force("link", d3.forceLink(links).strength(1).distance(20)); // <-E

          var link = svg.selectAll("line")
              .data(links)
            .enter().insert("line")
              .style("stroke", "#999")
              .style("stroke-width", "1px");

          var nodeElements = svg.selectAll("circle.node")
              .data(nodes)
            .enter().append("circle")
              .attr("r", r)
              .style("fill", function(d) {
                  return colors(d.parent && d.parent.data.name); // <-F
              })
              .style("stroke", "#000")
              .call(d3.drag() // <-G
                      .on("start", dragStarted)
                      .on("drag", dragged)
                      .on("end", dragEnded));

          force.on("tick", function(e) {
            link.attr("x1", function(d) { return d.source.x; })
                .attr("y1", function(d) { return d.source.y; })
                .attr("x2", function(d) { return d.target.x; })
                .attr("y2", function(d) { return d.target.y; });

            nodeElements.attr("cx", function(d) { return d.x; })
                .attr("cy", function(d) { return d.y; });
          });
    });

    function dragStarted(d) {
        d.fx = d.x;
        d.fy = d.y;
    }

    function dragged(d) {
        d.fx = d3.event.x;
        d.fy = d3.event.y;
    }

    function dragEnded(d) {
        d.fx = null;
        d.fy = null;
    }
</script>

</body>

</html>